package com.ljx.itbbs.server.article.dao;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.itbbs.common.domain.enums.CommonStatusEnum;
import com.ljx.itbbs.common.domain.vo.resp.CursorResp;
import com.ljx.itbbs.server.article.domain.entity.ArticleEntity;
import com.ljx.itbbs.server.article.domain.entity.CommentEntity;
import com.ljx.itbbs.server.article.domain.entity.LikeRecordEntity;
import com.ljx.itbbs.server.article.domain.vo.req.ArticleCommentReq;
import com.ljx.itbbs.server.article.domain.vo.resp.CommentResp;
import com.ljx.itbbs.server.article.mapper.CommentMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class CommentDao extends ServiceImpl<CommentMapper, CommentEntity> {

    public void increaseReplyNum(Long id) {
        lambdaUpdate().setSql("reply_num = reply_num + 1").eq(CommentEntity::getId, id).update();
    }


    public CursorResp<CommentEntity> getCommentList(ArticleCommentReq req) {
        LambdaQueryWrapper<CommentEntity> wrapper = new LambdaQueryWrapper<>();
        // 游标条件
        wrapper.eq(CommentEntity::getStatus, CommonStatusEnum.NORMAL.getStatus());
        wrapper.eq(CommentEntity::getArticleId, req.getArticleId());
        // 游标字段
        if (Objects.nonNull(req.getCursor())){
            wrapper.lt(CommentEntity::getId, req.getCursor());
        }
        // 游标方向
//        wrapper.orderByDesc(CommentEntity::getReplyNum, CommentEntity::getLikeNum, CommentEntity::getId);
        Page<CommentEntity> page = this.baseMapper.selectPage(req.plusPage(), wrapper);
        // 计算游标位置
        String cursor = Optional.ofNullable(CollectionUtil.getLast(page.getRecords()))
                .map(CommentEntity::getId)
                .map(String::valueOf)
                .orElse(null);
        return CursorResp.<CommentEntity>builder()
                .list(page.getRecords())
                .cursor(cursor)
                .isLast(page.getRecords().size() != req.getPageSize())
                .build();
    }

    public List<CommentEntity> getNewComment() {
        LambdaQueryWrapper<CommentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(CommentEntity::getCreateTime).last("LIMIT 5");

        return this.baseMapper.selectList(wrapper);
    }

    public void likeComment(Long commentId) {
        lambdaUpdate().setSql("like_num = like_num + 1")
                .eq(CommentEntity::getId, commentId)
                .update();
    }

    public void reduceCommentLikeNum(Long commentId) {
        lambdaUpdate().setSql("like_num = like_num - 1")
                .eq(CommentEntity::getId, commentId)
                .update();
    }
}
